package com.sunshine.lnuplus.internet

import android.R
import android.content.Context
import android.os.Build
import android.os.Looper
import android.util.Log
import androidx.fragment.app.FragmentManager
import com.google.gson.Gson
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.model.SuperBean
import com.sunshine.lnuplus.model.SuperData
import com.sunshine.lnuplus.model.SuperLessonBean
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.utils.CryptoUtils
import com.sunshine.lnuplus.utils.LoadLessonUtils
import es.dmoral.toasty.Toasty
import okhttp3.*
import java.io.IOException
import java.lang.Exception


class LoadSuperLesson {

    fun login(user: String,
              password: String,
              loginCallBack: LoginCallBack){
        val okHttpClient = OkHttpClient()
            .newBuilder()
            .followRedirects(false)
            .build()
        val requestBody = FormBody.Builder()
            .add("updateInfo", "false")
            .add("phoneModel", Build.MODEL)
            .add("password", CryptoUtils.superEncrypt(password))
            .add("phoneBrand", Build.BRAND)
            .add("channel", "xiaomi")
            .add("platform", "1")
            .add("versionNumber", "9.5.9")
            .add("account", CryptoUtils.superEncrypt(user))
            .add("phoneVersion", "${Build.VERSION.SDK_INT}")
            .build()
        val request = Request.Builder()
            .url("http://120.55.151.61/V2/StudentSkip/loginCheckV4.action")
            .post(requestBody)
            .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                loginCallBack.onFail("没有网络连接")
            }

            override fun onResponse(call: Call, response: Response) {
                var cookie = ""
                response.headers.forEach {
                    if(it.first == "Set-Cookie" && it.second[0].equals('J')){
                        cookie = it.second
                    }
                }
                if(cookie.isEmpty()){
                    loginCallBack.onFail("账号或密码错误")
                }else{
                    SuperData.cookie = cookie
                    try {
                        val jsonArray = JsonParser
                            .parseString(response.body?.string())
                            .asJsonObject
                            .getAsJsonObject("data")
                            .getAsJsonObject("student")
                            .getAsJsonObject("attachmentBO")
                            .getAsJsonArray("myTermList")

                        jsonArray.forEach {
                            var timeString = ""
                            try {
                                val jsonArray = JsonParser
                                    .parseString(it.toString())
                                    .asJsonObject
                                    .getAsJsonObject("courseTimeList")
                                    .getAsJsonArray("courseTimeBO")
                                jsonArray.forEach {time ->
                                    timeString +=
                                        time.asJsonObject.getAsJsonPrimitive("beginTimeStr").toString().substring(1, 3)+
                                                ":" +
                                                time.asJsonObject.getAsJsonPrimitive("beginTimeStr").toString().substring(3, 5) +
                                                "\n" +
                                                time.asJsonObject.getAsJsonPrimitive("endTimeStr").toString().substring(1, 3)+
                                                ":" +
                                                time.asJsonObject.getAsJsonPrimitive("endTimeStr").toString().substring(3, 5) +
                                                "|"
                                }
                                if(timeString[timeString.length - 1] == '|'){
                                    timeString = timeString.substring(0, timeString.length - 1)
                                }
                            }catch (e: Exception){

                            }

                            val superBean = SuperBean(
                                it.asJsonObject.getAsJsonPrimitive("beginYear").asString,
                                it.asJsonObject.getAsJsonPrimitive("maxCount").asInt,
                                it.asJsonObject.getAsJsonPrimitive("term").asString,
                                timeString
                            )
                            SuperData.superList.add(superBean)
                        }
                    }catch (e: Exception){
                        loginCallBack.onFail("$e 很可能是账号或者密码错误噢")
                    }
                    loginCallBack.onSuccess()
                }
            }
        })
    }

    fun load(
        which: Int,
        loginCallBack: LoginCallBack,
        repository: TimetableRepository,
        context: Context,
        fragmentManager: FragmentManager
    ){
        val okHttpClient = OkHttpClient()
            .newBuilder()
            .followRedirects(false)
            .build()
        val requestBody = FormBody.Builder()

            .add("phoneModel", Build.MODEL)
            .add("phoneBrand", Build.BRAND)
            .add("channel", "xiaomi")
            .add("beginYear", SuperData.superList[which].beginYear)
            .add("term", SuperData.superList[which].term)
            .add("platform", "1")
            .add("versionNumber", "9.5.9")
            .add("phoneVersion", "${Build.VERSION.SDK_INT}")
            .build()
        val request = Request.Builder()
            .url("http://120.55.151.61/V2/Course/getCourseTableFromServer.action")
            .header("Cookie",SuperData.cookie!!)
            .post(requestBody)
            .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                loginCallBack.onFail("没有网络连接")
            }

            override fun onResponse(call: Call, response: Response) {
                val body = response.body?.string()
                if(body.isNullOrEmpty()){
                    loginCallBack.onFail("课表解析失败")
                }else{
                    try {
                        val jsonArray = JsonParser
                            .parseString(body)
                            .asJsonObject
                            .getAsJsonObject("data")
                            .getAsJsonArray("lessonList")
                        jsonArray.forEach {
                            val superLessonBean: SuperLessonBean =
                                Gson().fromJson(it, object : TypeToken<SuperLessonBean>(){}.type)
                            SuperData.superLessonList.add(superLessonBean)
                        }
                        LoadLessonUtils.initSuperLesson(repository = repository, loginCallBack = loginCallBack, context = context, fragmentManager = fragmentManager)
                    }catch (e: Exception){
                        loginCallBack.onFail("$e 发生异常")
                    }
                }
            }
        })
    }
}